from django.conf import settings
from django.contrib.auth.backends import ModelBackend
import re

from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import JsonResponse
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData
from django.contrib.auth.decorators import login_required

from meiduo_mall.utils.response_code import RETCODE
from users.models import User
from . import constants


def get_user_by_account(account):
    """
    根据ａｃｃｏｕｎｔ查询用户
    :param account: 用户账户
    :return: 用户user
    """
    try:
        print('运行')
        if re.match(r'^1[3-8]\d{9}$',account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user

def generate_verify_email_url(user):
    """
    生成邮箱验证链接
    :param user: 当前登录用户
    :return: verify_url
    """
    serializer = Serializer(settings.SECRET_KEY,expires_in=constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    data = {'user_id':user.id,'email':user.email}
    token = serializer.dumps(data).decode()
    verify_url = settings.EMAIL_VERIFY_URL + '?token=' + token
    return verify_url

def check_verify_email_token(token):
    serializer = Serializer(settings.SECRET_KEY,expires_in=constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    try:
        data = serializer.loads(token)
    except BadData:
        return None
    else:
        user_id = data['user_id']
        email = data['email']
        try:
            user = User.objects.get(id=user_id,email=email)
        except User.DoesNotExist:
            return None
        else:
            return user


class UsernameMobileAuthBackend(ModelBackend):
    """
    自定义用户认证后端
    """


    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        重写用户认证方法
        :param request:请求对象
        :param username: 用户账户
        :param password: 用户密码
        :param kwargs: 其他参数
        :return: 用户user
        """
        if request is None:
            # 代表是后台登陆
            try:
                # 验证管理员
                user = User.objects.get(username=username,is_staff=True)
            except:
                user = None
            if user and user.check_password(password):
                return user
            return user
        user = get_user_by_account(username)
        if user and user.check_password(password):
            return user


class LoginRequireMixin(object):
    """验证用户是否登录拓展类"""

    @classmethod
    def as_view(cls,**initkwargs):
        view = super().as_view()
        return login_required(view)

# 继承LoginRequiredMixin类，重写handle_no_permission()方法
class LoginRequiredJSONMixin(LoginRequiredMixin):
    # 若用户未登录，直接返回json给前端
    def handle_no_permission(self):
        return JsonResponse({'code': RETCODE.ALLOWERR, 'errmsg': '用户未登录'})